package com.party.admin.web.controller.subject;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.subject.SubjectDeleteBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.article.ArticleOutput;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleGroup;
import com.party.core.model.subject.Subject;
import com.party.core.model.subject.SubjectApply;
import com.party.core.model.user.User;
import com.party.core.service.article.IArticleGroupService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.subject.ISubjectApplyService;
import com.party.core.service.subject.ISubjectService;
import com.party.core.service.user.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 专题应用
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/subject/apply")
public class SubjectApplyController {

	@Autowired
	private ISubjectService subjectService;

	@Autowired
	private ISubjectApplyService subjectApplyService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IArticleService articleService;

	@Autowired
	private IArticleGroupService articleGroupService;

	@Autowired
	private FileBizService fileBizService;
	
	@Autowired
	private CosBizService cosBizService;

	@Autowired
	private SubjectDeleteBizService subjectDeleteBizService;

	protected static Logger logger = LoggerFactory.getLogger(SubjectApplyController.class);

	/**
	 * 跳转至列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "applyList")
	public ModelAndView publishList(SubjectApply subjectApply, String applyId) {
		ModelAndView mv = new ModelAndView("subject/applyList");
		Subject subject = subjectService.get(subjectApply.getSubjectId());
		mv.addObject("subject", subject);
		return mv;
	}

	/**
	 * 栏目列表
	 * @param subjectId
	 * @param applyId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getApplyList")
	public AjaxResult getApplyList(String subjectId, String applyId) {
		SubjectApply subjectApply = new SubjectApply();
		subjectApply.setSubjectId(subjectId);
		subjectApply.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		List<SubjectApply> applies = subjectApplyService.list(subjectApply);

		String firstId = applyId;
		if (StringUtils.isEmpty(applyId) && applies.size() > 0) {
			firstId = applies.get(0).getId();
		}

		Map<String, Object> map = Maps.newHashMap();
		map.put("applies", applies);
		map.put("firstId", firstId);
		return AjaxResult.success(map);
	}

	@ResponseBody
	@RequestMapping(value = "loadJsonData")
	public Map<String, Object> loadJsonData(String applyId, String title, Page page) {
		Map<String, Object> map = new HashMap<String, Object>();
		SubjectApply subjectApply = subjectApplyService.get(applyId);
		map.put("subjectApply", subjectApply);
		List<Article> articles = new ArrayList<Article>();
		if (subjectApply.getType().equals("article")) {
			Article article = articleService.get(subjectApply.getTargetId());
			if (article != null) {
				articles.add(article);
			}
		} else if (subjectApply.getType().equals("channel")) {
			Article t = new Article();
			t.setTitle(title);
			t.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
			t.setArticleGroupId(subjectApply.getTargetId());
			page.setLimit(10);
			articles = articleService.webListPage(t, null, page);
		}
		List<ArticleOutput> articleOutputs = LangUtils.transform(articles, input -> {
			ArticleOutput articleOutput = ArticleOutput.transform(input);
			String content = "article/article_detail.html?id=" + input.getId();
			articleOutput.setPic(content);
			String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "article");
			String fileName = "detail_" + input.getId();
			String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
			articleOutput.setQrCodeUrl(qrCodeUrl);
			articleOutput.setApplyId(applyId);
			return articleOutput;
		});

		map.put("articles", articleOutputs);
		map.put("page", page);
		return map;
	}

	/**
	 * 读取列表数据
	 * 
	 * @param page
	 * @param subjectId
	 *            专题id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "publishListJson")
	public Map<String, Object> publishListJson(Page page, String subjectId) {
		page.setLimit(9);
		SubjectApply subjectApply = new SubjectApply();
		subjectApply.setSubjectId(subjectId);
		subjectApply.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		List<SubjectApply> applies = subjectApplyService.listPage(subjectApply, page);
		for (SubjectApply apply : applies) {
			Subject subject = subjectService.get(apply.getSubjectId());
			apply.setSubjectName(subject.getName());
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("datas", applies);
		map.put("page", page);
		return map;
	}

	/**
	 * 跳转至发布
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "applyForm")
	public ModelAndView applyForm(String id, String subjectId) {
		ModelAndView mv = new ModelAndView("subject/applyForm");
		if (StringUtils.isNotEmpty(id)) {
			SubjectApply apply = subjectApplyService.get(id);
			mv.addObject("apply", apply);
			if (apply.getType().equals("channel")) {
				ArticleGroup articleGroup = articleGroupService.get(apply.getTargetId());
				mv.addObject("articleGroup", articleGroup);
			}
		}
		Subject subject = subjectService.get(subjectId);
		mv.addObject("subject", subject);
		return mv;
	}

	/**
	 * 跳转至详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "applyDetail")
	public ModelAndView applyDetail(String id, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("subject/applyInfo");
		SubjectApply apply = subjectApplyService.get(id);
		Subject subject = subjectService.get(apply.getSubjectId());
		if (apply.getType().equals(SubjectApply.TYPE_ARTICLE) || apply.getType().equals(SubjectApply.TYPE_ARTICLE_GROUP)) {
			String url = "http://" + request.getServerName() //服务器地址
					+ ":"
					+ request.getServerPort()           //端口号
					+ apply.getUrl();

			apply.setUrl(url);
		}
		mv.addObject("subject", subject);
		mv.addObject("apply", apply);
		return mv;
	}

	/**
	 * 发布保存
	 * 
	 * @param apply
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxResult save(SubjectApply apply, BindingResult result, String channelPicture) throws Exception {
		AjaxResult ajaxResult = new AjaxResult();
		// 数据验证
		if (result.hasErrors()) {
			List<ObjectError> allErros = result.getAllErrors();
			ajaxResult.setDescription(allErros.get(0).getDefaultMessage());
			return ajaxResult;
		}

		User user = userService.findByLoginName("admin");

		if (StringUtils.isNotEmpty(apply.getId())) {
			SubjectApply t = subjectApplyService.get(apply.getId());
			MyBeanUtils.copyBeanNotNull2Bean(apply, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getType().equals("url")) {
				t.setTargetId(null);
			}

			if (t.getType().equals("channel")) {
				ArticleGroup articleGroup = articleGroupService.get(t.getTargetId());
				if (articleGroup == null) {
					articleGroup = new ArticleGroup();
					articleGroup.setName(apply.getName());
					articleGroup.setPicture(channelPicture);
					articleGroup.setCreateBy(user.getId());
					articleGroup.setUpdateBy(user.getId());
					articleGroup.setMemberId(RealmUtils.getCurrentUser().getId());
					articleGroup.setIsShow(1);
					String channelId = articleGroupService.insert(articleGroup);
					t.setTargetId(channelId);
					t.setUrl(SubjectApply.MIC_URL + "article/article_group_detail.html?id=" + channelId);
				} else {
					articleGroup.setPicture(channelPicture);
					articleGroup.setName(apply.getName());
					articleGroupService.update(articleGroup);
					t.setUrl(SubjectApply.MIC_URL +  "article/article_group_detail.html?id=" + articleGroup.getId());
				}
			}
			t.setUpdateDate(new Date());
			subjectApplyService.update(t);
		} else {
			apply.setCreateBy(user.getId());
			apply.setUpdateBy(user.getId());
			apply.setMemberId(RealmUtils.getCurrentUser().getId());

			if (apply.getType().equals("channel")) {
				ArticleGroup articleGroup = new ArticleGroup();
				articleGroup.setName(apply.getName());
				articleGroup.setPicture(channelPicture);
				articleGroup.setCreateBy(user.getId());
				articleGroup.setUpdateBy(user.getId());
				articleGroup.setMemberId(RealmUtils.getCurrentUser().getId());
				articleGroup.setIsShow(1);
				String channelId = articleGroupService.insert(articleGroup);
				apply.setTargetId(channelId);
				apply.setUrl(SubjectApply.MIC_URL +  "article/article_group_detail.html?id=" + channelId);
			}

			subjectApplyService.insert(apply);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("subjectId", apply.getSubjectId());
		map.put("applyId", apply.getId());
		ajaxResult.setData(map);
		ajaxResult.setSuccess(true);
		return ajaxResult;
	}

	/**
	 * 删除栏目
	 */
	@ResponseBody
	@RequestMapping(value = "delete")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AjaxResult delete(String applyId, String subjectId) {
		if (StringUtils.isEmpty(applyId)) {
			return AjaxResult.error("栏目编号不能为空");
		}
		SubjectApply subjectApply = subjectApplyService.get(applyId);
		if (SubjectApply.TYPE_ARTICLE_GROUP.equals(subjectApply.getType())) {
			List<Article> articles = articleService.getByArticleGroupId(subjectApply.getTargetId());
			if (articles.size() > 0) {
				return AjaxResult.error("栏目已存在文章");
			}
		} else if (SubjectApply.TYPE_ARTICLE.equals(subjectApply.getType())) {
			Article article = articleService.get(subjectApply.getTargetId());
			if (null != article) {
				return AjaxResult.error("栏目已存在文章");
			}
		}
		boolean result = subjectDeleteBizService.deleteSubjectApplyBiz(applyId);
		if (result) {
			return AjaxResult.success((Object) subjectId);
		} else {
			return AjaxResult.error("删除失败");
		}
	}

	/**
	 * 更新排序
	 * @param applyId
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping("updateSort")
	public AjaxResult updateSort(String applyId, String type) {
		SubjectApply subjectApply = subjectApplyService.get(applyId);
		List<SubjectApply> subjectApplies = subjectApplyService.getBySubjectId(subjectApply.getSubjectId());
		if (subjectApply.getSort() == null) {
			return AjaxResult.error("请先填写序号");
		}
		if (type.equals("up")) {
			if (subjectApply.getSort() != 1) {
				SubjectApply newApply = null;
				Integer sort = subjectApply.getSort() - 1;
				for (SubjectApply s : subjectApplies) {
					if ((s.getSort().equals(sort) || s.getSort() - 1  == sort) && !s.getId().equals(applyId)) {
						newApply = s;
						break;
					}
				}
				if (newApply != null) {
					newApply.setSort(newApply.getSort() + 1);
					subjectApplyService.update(newApply);
				}
				subjectApply.setSort(sort);
				subjectApplyService.update(subjectApply);
			} else {
				return AjaxResult.error("已经是第一位了");
			}
		} else if (type.equals("down")) {
			if (subjectApply.getSort() != subjectApplies.size()) {
				SubjectApply newApply = null;
				Integer sort = subjectApply.getSort() + 1;
				for (SubjectApply s : subjectApplies) {
					if ((s.getSort().equals(sort) || s.getSort() + 1  == sort) && !s.getId().equals(applyId)) {
						newApply = s;
						break;
					}
				}
				if (newApply != null) {
					newApply.setSort(newApply.getSort() - 1);
					subjectApplyService.update(newApply);
				}
				subjectApply.setSort(sort);
				subjectApplyService.update(subjectApply);
			} else {
				return AjaxResult.error("已经是最后一位了");
			}
		}
		return AjaxResult.success();
	}


	/**
	 * 拖曳更新排序
	 * @param jsonStr 排序json字符串
	 * @return
	 */
	@ResponseBody
	@RequestMapping("dragUpdateSort")
	public AjaxResult dragUpdateSort(String jsonStr) {
		if (StringUtils.isEmpty(jsonStr)) {
			return AjaxResult.error("栏目排序json字符串不能为空");
		}
		Map<String, Integer> resultMap = JSONObject.parseObject(jsonStr, Map.class);
		for (Map.Entry<String, Integer> result : resultMap.entrySet()) {
			String id = result.getKey(); // 文章id
			Integer newSort = result.getValue(); // 排序号
			SubjectApply apply = subjectApplyService.get(id);
			apply.setSort(newSort);
			subjectApplyService.update(apply);
		}
		return AjaxResult.success();
	}
}
